package org.raymond.iworks.gateway.authenticate;

import org.apache.commons.lang3.StringUtils;
import org.raymond.iworks.apis.ITSysUserServiceApi;
import org.raymond.iworks.apis.common.ErrorCode;
import org.raymond.iworks.apis.common.Result;
import org.raymond.iworks.apis.exception.BaseException;
import org.raymond.iworks.core.security.Certification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class UsernameAuthentication implements Authentication {
    @Autowired
    private ITSysUserServiceApi itSysUserServiceApi;

    @Override
    public String authenticate(Certification certification) throws BaseException {
        Result<String> result = null;
        try {
            CompletableFuture<Result<String>> future = CompletableFuture.supplyAsync(()->itSysUserServiceApi.usernameAuthentication(certification.getUsername(), certification.getPassword()));
            result = future.get();
            if (result == null || !result.isSuccess() || StringUtils.isBlank(result.getData())) {
                throw new BaseException(ErrorCode.UNAUTHORIZED, "certification authenticate failed");
            }
        }catch(ExecutionException | InterruptedException e){
            throw new BaseException(ErrorCode.UNAUTHORIZED, String.format("async execute error: %s", e.getMessage()));
        }
        return result.getData();
    }
}
